import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { type ProColumns, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Card,
  Col,
  Dropdown,
  Empty,
  Input,
  Modal,
  message,
  Row,
  Space,
  Spin,
  Switch,
  Tree,
} from "antd";
import { useEffect, useRef, useState } from "react";
import PopconfirmButton from "@/components/PopconfirmButton";
import {
  addCategory,
  deleteCategory,
  deleteProduct,
  editCategory,
  getProductCategoryList,
  getProductList,
  updateProductStatus,
} from "@/services/product";
import { sleep } from "@/utils";
import { gutter } from "../const/keys";
import { getToken } from "../utils";
import AddModal from "./AddModal";
import DetailModal from "./DetailModal";
import ImportModal from "./ImportModal";
import MoveModal from "./MoveModal";

const getParentId = (value: string, data: any[]): string | undefined => {
  for (const item of data) {
    if (item.children?.some((child: any) => child.value === value)) {
      return item.value;
    }
    if (item.children && item.children?.length > 0) {
      const parentId = getParentId(value, item.children);
      if (parentId) return parentId;
    }
  }
  return undefined;
};

// 🔍 过滤树结构，保留匹配项及其父级
const filterTree = (treeData: any[], keyword: string): any[] => {
  if (!keyword) return treeData;
  const loop = (nodes: any[]): any[] => {
    return nodes
      .map((node) => {
        const match = node.title.includes(keyword);
        let children: any[] = [];
        if (node.children && node.children?.length > 0) {
          children = loop(node.children);
        }
        if (match || children?.length > 0) {
          return {
            ...node,
            children,
          };
        }
        return null;
      })
      .filter(Boolean);
  };
  return loop(treeData);
};

// 展开匹配节点
// const getExpandedKeys = (treeData: any[], keyword: string): React.Key[] => {
//   const keys: React.Key[] = [];
//   const loop = (nodes: any[]) => {
//     nodes.forEach((node) => {
//       if (node.title.includes(keyword)) {
//         keys.push(node.value);
//       }
//       if (node.children && node.children?.length > 0) {
//         loop(node.children);
//       }
//     });
//   };
//   loop(treeData);
//   return keys;
// };

const App = () => {
  const [treeData, setTreeData] = useState<any[]>([]);
  const [originalTreeData, setOriginalTreeData] = useState<any[]>([]);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [importOpen, setImportOpen] = useState<boolean>(false);
  const [moveOpen, setMoveOpen] = useState<boolean>(false);
  const myTable = useRef<any>(null);
  const [editCategoryInfo, setEditCategoryInfo] = useState<{
    type: any;
    open: boolean;
    value: any;
    title: string | undefined;
  }>({
    type: undefined,
    open: false,
    value: undefined,
    title: undefined,
  });
  const [record, setRecord] = useState<any>({});
  const [viewOpen, setViewOpen] = useState<boolean>(false);
  const [productCategoryId, setProductCategoryId] = useState<number>();
  const [categoryName, setCategoryName] = useState<string>("");
  const [openAddModal, setOpenAddModal] = useState<boolean>(false);
  const [id, setId] = useState<number | undefined>();
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const columns: ProColumns<Record<string, any>, "text">[] = [
    {
      title: "产品编码",
      dataIndex: "productNumber",
      search: false,
    },
    {
      title: "产品名称",
      dataIndex: "productName",
    },
    {
      title: "型号",
      dataIndex: "modelSpecification",
      render: (_: any, record: any) => {
        return (
          <Button
            onClick={() => {
              setRecord(record);
              setViewOpen(true);
            }}
            type="link"
          >
            {record.modelSpecification}
          </Button>
        );
      },
    },
    {
      title: "品牌",
      dataIndex: "brand",
    },
    {
      title: "售价",
      dataIndex: "guidancePrice",
      search: false,
      render: (_: any, record: any) => {
        //除以100，保留两位数
        return (record.guidancePrice / 100).toFixed(2);
      },
    },
    {
      title: "单位",
      dataIndex: "unit",
      search: false,
    },
    {
      title: "启用状态",
      dataIndex: "productStatus",
      search: false,
      render: (_: any, record: any) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            onChange={async (e) => {
              const { success } = await updateProductStatus({
                id: record.id,
                productStatus: e ? 1 : 0,
              });
              await myTable.current.reload();
              if (success) {
                message.success("操作成功");
              }
            }}
            defaultChecked={record.productStatus === 1}
          />
        );
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      width: 200,
      render: (_: any, record: any) => [
        <Button
          key="edit"
          size="small"
          type="link"
          ghost
          //禁用的时候不触发onClick

          icon={<EditOutlined />}
          onClick={() => {
            setOpenAddModal(true);
            setId(record.id);
          }}
        >
          编辑
        </Button>,

        <PopconfirmButton
          title={`确定要删除 ${record.productName} 吗？`}
          icon={<DeleteOutlined />}
          key="delete"
          type="link"
          size="small"
          danger={false}
          onConfirm={() => {
            del([record.id]);
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  const [query, setQuery] = useState<any>({});
  //下载文件 "/api/ying/product/export"
  const exportData = async () => {
    const { pageInfo } = myTable.current;
    const submitData = { ...query, ...pageInfo, productCategoryId };
    delete submitData.total;
    // config.headers = {
    //         ...config.headers,
    //         Authorization: `Bearer ${getToken()}`,
    //       };
    setLoading(true);
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/ying/product/export", true);
    // aplication/json
    xhr.setRequestHeader("Authorization", `Bearer ${getToken()}`);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    //
    xhr.send(JSON.stringify(submitData));
    // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.responseType = "blob";

    xhr.onload = async function () {
      if (this.status === 200) {
        const blob = this.response;
        const downloadUrl = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "产品数据导出.xlsx";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadUrl);
        await sleep(2000);
        setLoading(false);
      } else {
        message.error("导出失败");
        setLoading(false);
      }
    };
  };

  const del = async (ids: any) => {
    const { success } = await deleteProduct(ids);
    if (success) {
      message.success("删除成功");
      myTable.current.reload();
      setSelectedKeys([]);
      setSelectedRowKeys([]);
    }
  };

  const getData = async () => {
    setSpinning(true);
    const { data } = await getProductCategoryList({});

    const resetTree = (data: any, parentId?: undefined) => {
      return data?.map((item: any) => ({
        title: item.categoryName,
        value: item.id,
        parentId,
        children: resetTree(item.subList || [], item.id),
      }));
    };

    const formattedTree = resetTree(data);
    setTreeData(formattedTree);
    setOriginalTreeData(formattedTree); // 保存原始树
    setSpinning(false);
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <>
      <Row gutter={[gutter, gutter]} wrap={false}>
        {/* 左侧分类树 */}
        <Col flex={"250px"}>
          <Card title="产品分类" style={{ border: "none", height: "100%" }}>
            <Row gutter={[gutter, gutter]}>
              <Col span={24}>
                <Input.Search
                  placeholder="搜索产品分类"
                  value={categoryName}
                  onSearch={(value) => {
                    const keyword = value.trim();
                    if (!keyword) {
                      setTreeData(originalTreeData);
                      return;
                    }
                    const filtered = filterTree(originalTreeData, keyword);
                    // const expanded = getExpandedKeys(originalTreeData, keyword);
                    setTreeData(filtered);
                  }}
                  onChange={(ev) => {
                    setCategoryName(ev.target.value);
                  }}
                  allowClear
                />
              </Col>

              <Col span={24}>
                <Spin spinning={spinning}>
                  {treeData?.length === 0 && (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                  <Tree
                    style={{ width: "100%" }}
                    treeData={treeData}
                    showIcon
                    blockNode
                    selectedKeys={selectedKeys}
                    // expandedKeys={allKeys}

                    onSelect={(a, b) => {
                      setSelectedKeys(a);
                      const selectedValue = a[0];
                      if (selectedValue) {
                        setProductCategoryId(Number(b.node.value));
                      } else {
                        setProductCategoryId(undefined);
                      }
                    }}
                    titleRender={(node: any) => {
                      // 🔥 高亮匹配关键词
                      const index = node.title.indexOf(categoryName);
                      const beforeStr = node.title.substr(0, index);
                      const afterStr = node.title.substr(
                        index + categoryName?.length
                      );
                      const title =
                        index > -1 && categoryName ? (
                          <span>
                            {beforeStr}
                            <span style={{ color: "red" }}>{categoryName}</span>
                            {afterStr}
                          </span>
                        ) : (
                          node.title
                        );

                      return (
                        <>
                          {title}
                          <span
                            style={{
                              position: "absolute",
                              right: 0,
                            }}
                            onClick={(ev) => {
                              ev.stopPropagation();
                            }}
                          >
                            <Dropdown
                              trigger={["click"]}
                              menu={{
                                items: [
                                  {
                                    key: 1,
                                    label: "重命名",
                                    onClick: () => {
                                      setEditCategoryInfo({
                                        type: 1,
                                        open: true,
                                        value: node.value,
                                        title: node.title,
                                      });
                                    },
                                  },
                                  {
                                    key: 2,
                                    label: "新增子目录",
                                    onClick: async () => {
                                      setEditCategoryInfo({
                                        type: 2,
                                        open: true,
                                        value: node.value,
                                        title: "",
                                      });
                                    },
                                  },
                                  {
                                    key: 3,
                                    label: "删除",
                                    onClick: async () => {
                                      Modal.confirm({
                                        title: "信息提示",
                                        onOk: async () => {
                                          const { success } =
                                            await deleteCategory({
                                              id: node.value,
                                            });
                                          if (success) {
                                            message.success("删除成功");
                                            getData();
                                          }
                                        },
                                        content: (
                                          <>
                                            <h3>是否确定删除</h3>
                                            <div style={{ color: "gray" }}>
                                              删除此目录其下产品将进入临时产库
                                            </div>
                                          </>
                                        ),
                                      });
                                    },
                                  },
                                ],
                              }}
                            >
                              <span onClick={(e) => e.preventDefault()}>
                                <Space>
                                  <InfoCircleOutlined />
                                </Space>
                              </span>
                            </Dropdown>
                          </span>
                        </>
                      );
                    }}
                  />
                </Spin>
              </Col>
            </Row>
          </Card>
        </Col>

        {/* 右侧 ProTable */}
        <Col flex={"auto"}>
          <ProTable
            scroll={{ x: 1000 }}
            rowKey={"id"}
            actionRef={myTable}
            rowSelection={{
              selectedRowKeys,
              onChange: (keys) => setSelectedRowKeys(keys),
            }}
            title={() => (
              <Row gutter={10}>
                <Col>
                  <Button
                    disabled={selectedRowKeys?.length === 0}
                    size="small"
                    onClick={() => {
                      setMoveOpen(true);
                    }}
                  >
                    批量移动
                  </Button>
                </Col>
                <Col>
                  <PopconfirmButton
                    title={`确定删除选中的 ${selectedRowKeys?.length} 个产品吗？`}
                    danger
                    disabled={selectedRowKeys?.length === 0}
                    size="small"
                    onConfirm={async () => {
                      del(selectedRowKeys);
                    }}
                  >
                    批量删除
                  </PopconfirmButton>
                </Col>
              </Row>
            )}
            onReset={() => {
              setProductCategoryId(undefined);
              setSelectedRowKeys([]);
              setSelectedKeys([]);
            }}
            columns={columns}
            toolBarRender={() => [
              <Button
                type="primary"
                key="add"
                size="small"
                ghost
                icon={<PlusOutlined />}
                onClick={() => setOpenAddModal(true)}
              >
                新建
              </Button>,
              <Button
                loading={loading}
                onClick={exportData}
                key="daoru"
                size="small"
                icon={<ArrowDownOutlined />}
              >
                导出
              </Button>,
              <Button
                key="daoru"
                size="small"
                icon={<ArrowUpOutlined />}
                onClick={() => {
                  setImportOpen(true);
                }}
              >
                批量导入
              </Button>,
            ]}
            params={{
              productCategoryId,
            }}
            request={async (params) => {
              const { success, rows, total } = await getProductList({
                ...params,
                pageNum,
                pageSize,
              });
              setQuery(params);
              return { data: rows, total, success };
            }}
            pagination={{
              showSizeChanger: true,
              pageSize,
              current: pageNum,
              onChange: (page, size) => {
                setPageNum(page);
                setPageSize(size);
              },
            }}
          />
        </Col>
      </Row>

      {/* 编辑分类弹窗 */}
      {editCategoryInfo.open && (
        <Modal
          width={400}
          title="信息提示"
          open
          onCancel={() => {
            setEditCategoryInfo({
              type: undefined,
              open: false,
              title: undefined,
              value: undefined,
            });
          }}
          onOk={async () => {
            const parentCategoryId =
              getParentId(editCategoryInfo.value, treeData) || 0;
            const { success } =
              editCategoryInfo.type === 1
                ? await editCategory({
                    categoryName: editCategoryInfo.title,
                    id: editCategoryInfo.value,
                    parentCategoryId,
                  })
                : await addCategory({
                    categoryName: editCategoryInfo.title,
                    parentCategoryId: editCategoryInfo.value,
                  });

            if (success) {
              getData();
              setEditCategoryInfo({
                type: undefined,
                open: false,
                title: undefined,
                value: undefined,
              });
              message.success("操作成功");
            }
          }}
          okButtonProps={{
            disabled: editCategoryInfo.title === "",
          }}
        >
          <Row gutter={[10, 10]}>
            <Col span={24}>请输入目录名称</Col>
            <Col span={24}>
              <Input
                placeholder="请输入目录名称"
                value={editCategoryInfo.title}
                maxLength={15}
                onChange={(e) => {
                  setEditCategoryInfo({
                    ...editCategoryInfo,
                    title: e.target.value,
                  });
                }}
              />
            </Col>
          </Row>
        </Modal>
      )}

      {/* 新建产品弹窗 */}
      {openAddModal && (
        <AddModal
          id={id}
          onClose={(reflash) => {
            if (reflash) {
              setSelectedKeys([]);
              setProductCategoryId(undefined);
              myTable.current.reload();
            }
            setOpenAddModal(false);
            setId(undefined);
          }}
        />
      )}

      {importOpen ? (
        <ImportModal
          onClose={(reflash) => {
            if (reflash) {
            }
            myTable.current?.reload();
            setImportOpen(false);
          }}
        />
      ) : null}

      {moveOpen ? (
        <MoveModal
          selectedRowKeys={selectedRowKeys as number[]}
          onClose={(reflash) => {
            setMoveOpen(false);
            if (reflash) {
              setSelectedRowKeys([]);
              myTable.current?.reload();
            }
          }}
        />
      ) : null}
      {viewOpen ? (
        <DetailModal
          data={record}
          onClose={() => {
            setViewOpen(false);
          }}
        />
      ) : null}
    </>
  );
};

export default App;
